package com.bgs.travelapp.userManagement.service.impl;

import com.bgs.travelapp.config.ScenicConfigProperties;
import com.bgs.travelapp.fileManager.service.FileManagerService;
import com.bgs.travelapp.menu.entity.MenuEntity;
import com.bgs.travelapp.menu.mapper.MenuMapper;
import com.bgs.travelapp.menu.service.MenuService;
import com.bgs.travelapp.page.MyPageHelper;
import com.bgs.travelapp.page.PageRequest;
import com.bgs.travelapp.page.PageResult;
import com.bgs.travelapp.result.CommonResult;
import com.bgs.travelapp.role.entity.RoleEntity;
import com.bgs.travelapp.role.mapper.RoleMapper;
import com.bgs.travelapp.userManagement.entity.UserManagementEntity;
import com.bgs.travelapp.userManagement.mapper.UserManagementMapper;
import com.bgs.travelapp.userManagement.service.UserManagementService;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * gpd 2022-07-10 20:13:00
 * 后端展示--用户管理
 */
@Service
public class UserManagementServiceImpl implements UserManagementService {

    @Resource
    UserManagementMapper userManagementMapper;

    @Resource
    FileManagerService fileManagerService;

    @Resource
    RoleMapper roleMapper;

    @Resource
    MenuMapper menuMapper;

    /**
     * 用户新增 （后端---用户管理）
     * gpd 2022-07-10 20:13:00
     * @Parma multipartRequest, userManagement
     */
    @Override
    public Integer saveUser(MultipartRequest multipartRequest, UserManagementEntity userManagementEntity) {
        MultipartFile file = multipartRequest.getFile("file");
        Integer fileId = 0;
        if (file != null) {
            fileId = fileManagerService.uploadPicture(file);
        }
        userManagementEntity.setDelFlag(1);
        userManagementEntity.setAvatarId(fileId);
        userManagementEntity.setCreateTime(new Date());
        String password = userManagementEntity.getPassword();
        String s = DigestUtils.md5DigestAsHex(password.getBytes());
        userManagementEntity.setPassword(s);
        int i = userManagementMapper.insertSelective(userManagementEntity);
        if (i > 0) {
            System.out.println("新增成功");
        } else {
            System.out.println("新增失败");
        }
        return i;
    }

    /**
     * 分页全查+模糊查（用户名称、登录名称、性别、角色名称、年龄） （后端---用户管理）
     * gpd 2022-07-10 20:23:00
     * @param pageRequest
     * @param userName
     * @param loginName
     * @param sex
     * @param roleName
     * @param age
     * @return
     */
    @Override
    public PageResult userAllList(PageRequest pageRequest, String userName, String loginName, String sex, String roleName, String age) {
        MyPageHelper.startPage(pageRequest);
        Example example = new Example(UserManagementEntity.class);
        example.createCriteria().andEqualTo("delFlag", 1).andLike("userName", "%" + userName + "%").andLike("loginName", "%" + loginName + "%").andLike("sex", "%" + sex + "%").andLike("roleName", "%" + roleName + "%").andLike("age", "%" + age + "%");
        PageResult pageResult = MyPageHelper.pageInfo(userManagementMapper.selectByExample(example));
        return pageResult;
    }

    /**
     * （后端---用户管理）
     * 用户修改
     * gpd 2022-07-10 20:36:00
     * @param userManagementEntity
     * @return
     */
    @Override
    public Integer updateUser(MultipartRequest multipartRequest, UserManagementEntity userManagementEntity) {
        MultipartFile file = multipartRequest.getFile("file");
        Integer fileId = 0;
        if (file != null) {
            fileId = fileManagerService.uploadPicture(file);
            userManagementEntity.setAvatarId(fileId);
        }
        String password = userManagementEntity.getPassword();
        String s = DigestUtils.md5DigestAsHex(password.getBytes());
        userManagementEntity.setPassword(s);
        userManagementEntity.setUpdateTime(new Date());
        return userManagementMapper.updateByPrimaryKeySelective(userManagementEntity);
    }

    /**
     * （后端---用户管理）
     * 删除用户
     * gpd 2022-07-10 20:48:00
     * @param id
     * @return
     */
    @Override
    public Integer deleteUser(Integer id) {
        UserManagementEntity userManagementEntity = new UserManagementEntity();
        userManagementEntity.setDelFlag(0);
        userManagementEntity.setId(id);
        return userManagementMapper.updateByPrimaryKeySelective(userManagementEntity);
    }

    /**
     * 根据账号密码登录
     * 后端--登录
     * gpd 2022-08-22 10点30分
     * @param loginName
     * @param password
     * @return
     */
    @Override
    public CommonResult loginByUser(String loginName, String password) {
        UserManagementEntity userManagementEntity = new UserManagementEntity();
        userManagementEntity.setLoginName(loginName);
        String md5Str = DigestUtils.md5DigestAsHex(password.getBytes());
        UserManagementEntity userManagement = userManagementMapper.selectOne(userManagementEntity);
        // 创建时间
        Date createTime = new Date();
        // 时间格式初始化
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        String createTimeSdf = sdf.format(createTime);
        String token = Base64Utils.encodeToString((userManagementEntity.getLoginName()+createTimeSdf+userManagementEntity.getPassword()).getBytes());
        if(userManagement!=null){
            Map<Object,Object> map = new HashMap<>();
            map.put("user",userManagement);
            map.put("token",token);
            return CommonResult.ok(map);
        }else {
            return CommonResult.error("999");
        }
    }

    /**
     * 获取用户权限
     * 后端---动态菜单
     * gpd 2022-08-22 11点17分
     * @param loginName
     * @return
     */
    @Override
    public CommonResult getUserRights(String loginName) {
        UserManagementEntity userManagementEntity = new UserManagementEntity();
        userManagementEntity.setLoginName(loginName);
        //查询该用户的信息
        UserManagementEntity userManagement = userManagementMapper.selectOne(userManagementEntity);
        RoleEntity roleEntity = new RoleEntity();
        roleEntity.setId(userManagement.getRoleId());
        //查询该用户的权限
        RoleEntity role = roleMapper.selectOne(roleEntity);
        //将权限id切分
        String power = role.getJurisdiction();
        String [] strings = power.split(",");
        ArrayList<MenuEntity> menuEntities =new ArrayList<>();
        //根据权限id找到对应的菜单信息
        for(String s: strings){
            int i  = Integer.parseInt(s);
            MenuEntity menu = new MenuEntity();
            menu.setId(i);
            MenuEntity menuEntity = menuMapper.selectOne(menu);
            menuEntities.add(menuEntity);
        }
        ArrayList<MenuEntity> newMenuEntity = new ArrayList<>();
        for(MenuEntity menuEntity : menuEntities){
            if(menuEntity.getParentId()==0){
                newMenuEntity.add(getChild(menuEntity,menuEntities));
            }
        }
        return CommonResult.ok(newMenuEntity);
    }

    /**
     * 新增修改校验登录账号
     * 后端---后端用户账号管理
     * gpd 2022-08-24 15点24分
     * @param loginName
     * @return
     */
    @Override
    public List<UserManagementEntity> checkLoginName(String loginName) {
        UserManagementEntity userManagementEntity = new UserManagementEntity();
        userManagementEntity.setLoginName(loginName);
        return userManagementMapper.select(userManagementEntity);
    }

    private MenuEntity getChild(MenuEntity menuEntity, ArrayList<MenuEntity> menuEntities) {
        List<MenuEntity> newMenuList = new ArrayList<>();
        for(MenuEntity menu : menuEntities){
            if(menuEntity.getId()==menu.getParentId()){
                newMenuList.add(getChild(menu,menuEntities));
            }
        }
        menuEntity.setChilds(newMenuList);
        return menuEntity;
    }


}
